﻿-- =============================================
-- Author:		Taylor Chase
-- Create date: 2 November 2015
-- Description:	Receives an ID, a type, and a comma-separated list of attribute names and values and writes them to the appropriate locations in the database.
-- =============================================
CREATE PROCEDURE [dbo].[WriteDataToDB] 
	-- Add the parameters for the stored procedure here
	@RequestorEntityID int, 
	@DataTableType nvarchar(50),
	@JSONData nvarchar(max),
	@DataID int = -1
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	--IF(SYSTEM_USER <> 'mboadev') BEGIN
	--	SET @RequestorEntityID = NULL
	--	SELECT @RequestorEntityID = EntityID FROM Attributes A INNER JOIN DefinedAttributes DA ON A.AttributeID = DA.AttributeID  
	--	WHERE AttributeName = 'Logon' AND AttributeValueString = SYSTEM_USER
	--	IF @RequestorEntityID IS NULL BEGIN
	--		DELETE FROM #JSONTable
	--		INSERT INTO #JSONTable
	--		SELECT * FROM parseJSON('{"DataError":"The user ' + SYSTEM_USER + ' cannot be found in the database."}')
	--	END
	--END

	-- These two steps create a temporary table that has the same structure as the
	-- Hierarchy table type.
	DECLARE @JSONTemplate Hierarchy;
	SELECT * INTO #JSONTable FROM @JSONTemplate;
	INSERT INTO #JSONTable
	SELECT * FROM parseJSON(@JSONData);
	
	IF @DataTableType = 'Entity'
		EXEC dbo.WriteDataToDB_EntityAttributes @RequestorEntityID,@DataID, @JSONData;
	ELSE IF @DataTableType = 'EntityRelationship'
		EXEC dbo.WriteDataToDB_EntityRelationships @RequestorEntityID;
	ELSE IF @DataTableType = 'EntityType'
		RETURN 2
	ELSE IF @DataTableType = 'EntityRelationshipType'
		RETURN 3
	ELSE IF @DataTableType = 'AttributeDefinition'
		RETURN 2
	ELSE IF @DataTableType = 'AttributeLookupDefinition'
		RETURN 2
	ELSE IF @DataTableType = 'DerivedAttributeDefinition'
		RETURN 2
	ELSE IF @DataTableType = 'TimeDivision'
		RETURN 2
	ELSE IF @DataTableType = 'TimeDivisionType'
		RETURN 2
	ELSE IF @DataTableType = 'DefinedMeetingPeriod'
		RETURN 3
	ELSE IF @DataTableType = 'DayType'
		RETURN 3
	ELSE IF @DataTableType = 'RelationshipChanger'
		RETURN 3
	ELSE IF @DataTableType = 'SecurityAttributeAccess'
		RETURN 3
	ELSE IF @DataTableType = 'DefinedDisplayFormats'
		RETURN 3
	ELSE
		RETURN 4
	
	-- This takes the result of the WriteData procedure and returns the same parameters
	-- it received in order to make sure the information was passed correctly
	INSERT INTO @JSONTemplate SELECT * FROM #JSONTable;
	SELECT @JSONData = dbo.ToJSON(@JSONTemplate);
	--SELECT count(*),'Joey' FROM @JSONTemplate
	SELECT @RequestorEntityID RequestorEntityID,@DataTableType DataTableType,@DataID DataID,@JSONData JSONData
	RETURN 0
END
